import React, { useRef, useState, useEffect } from 'react';
import styles from './index.less';
import { connect } from 'dva';
import exploreApi, { DayListenData } from '@/services/explore';
import { TracksData, getTracks } from '@/services/play';
import { PlayState } from '@/models/player';

const SideBar = ({
  children,
  history,
  route: { routes },
  location: { pathname },
  playTracks,
}) => {
  const defaultSelectedKeys = [pathname.slice(1)];
  const defaultOpenKeys = ['find', 'my'];
  const [trackList, setTrackList] = useState([]);
  useEffect(() => {
    (async () => {
      try {
        const { data, }: { data: DayListenData; } = await exploreApi.getDailyListen();
        const res = data.dailyListenCategoryList.reduce((arr, item) => {
          const trackArr = item.trackList.map((track) => {
            const { trackId } = track;
            return trackId;
          });
          return [...arr, ...trackArr];
        }, []);
        setTrackList(res);
      } catch (e) {
        // todo
      }
    })();
  })
  const handlePlayDayListen = async () => {
    try {
      // 点击播放按钮
      const rsp: { data: TracksData } = await getTracks(trackList);
      const playlist = rsp.data.tracksForAudioPlay;
      const info = {
        albumId: '',
        hasMore: false,
        currentTrack: playlist[0],
        currentIndex: 0,
        playlist,
      };
      playTracks(info);
    } catch (e) {
      // todo
    }
  };

  const dateArr = new Date().toDateString().split(' ');
  const day = dateArr[2];
  const month = dateArr[1];

  return (
    <div className={styles.sidebar}>
      <div className={styles.widget}>
        <div className={styles.date}>
          <div className={styles.playCon} onClick={handlePlayDayListen} />
          <span className={styles.month}> {month}</span>
          <span className={styles.day}>{day}</span>
        </div>
      </div>
    </div>
  );
}


export default connect(
  null,
  (dispatch) => {
    return {
      playTracks(payload) {
        dispatch({ type: 'track/updateTrack', payload });
        dispatch({
          type: 'player/updateState',
          payload: { playState: PlayState.PLAYING, played: 0.0 },
        });
      },
    };
  },
)(SideBar);
